<template>
  <el-card :body-style="{ padding: '20px' }">
    <el-form label-width="120px" inline>
      <!-- 表单元素 -->
      <el-form-item class="mr-50" size="small" >
        <el-input v-model="username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item class="mb-30" size="small">
        <!-- 查询与情况的按钮 -->
        <el-button icon="el-icon-search" type="primary" @click="search">查询</el-button>
        <el-button @click="resetSearch">清空</el-button>
      </el-form-item>
    </el-form>
    <el-form class="mb-20" size="small">
      <el-button type="primary" @click="showAddUser">添加</el-button>
      <el-button 
        type="danger" 
        :disabled="!selectedIds.length" 
        @click="deleteUsers"
        >批量删除</el-button>
    </el-form>

    <el-table 
      :data="tableData" 
      border 
      style="width: 100%; margin: 20px 0" 
      @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="150">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称">
      </el-table-column>
      <el-table-column prop="roleName" label="角色列表" width="200">
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="180">
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" width="180">
      </el-table-column>
      <el-table-column prop="operate" label="操作" width="200" cell-style>
        <template #default="{ row, $index }">
          <el-button size="small" type="info" class="el-icon-user" title="分配角色" @click="showAssignRole(row)" />
          <el-button style="margin-right: 10px;" size="small" type="primary" class="el-icon-edit-outline" title="修改用户" @click="showUpdateUser(row)" />
          
          <el-popconfirm 
            :title="`确定删除${row.username}吗?`" @confirm="removeUser(row)">
            <el-button size="small" type="danger" slot="reference" class="el-icon-delete" title="删除用户"  />
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
      :page-sizes="[5, 10, 20, 30]" :page-size="limit" layout="prev, pager, next, jumper,->,sizes,total " :total="total">
    </el-pagination>
    <!-- 对话框的结构 -->
    <el-dialog title="添加用户" :visible.sync="dialogUserVisible" top>
      <!-- :model="user" -->
      <el-form :model="user" :rules="userRules" ref="user">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input v-model="user.username" ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="120px">
          <el-input v-model="user.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" label-width="120px" prop="password">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible"  top>
      <!-- :model="user" -->
      <el-form label-width="120px">
        <el-form-item label="用户名" label-width="80px">
          <el-input v-model="users.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox :model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="userRoleIds"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="role in allRoles"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="assignRole">保存</el-button>
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="dialogUpdataUserVisible" top>
      <!-- :model="user" -->
      <el-form label-width="120px" :model="user" :rules="userRules" ref="user" >
        <el-form-item label="用户名" label-width="80px" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="80px" prop="nickName">
          <el-input v-model="user.nickName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdataUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- card body -->
  </el-card>
</template>

<script>
import userApi from '@/api/acl/user'
import cloneDeep from 'lodash/cloneDeep'


export default {
  data() {
    return {
      // searchObj: {
        // 包含请求搜索条件数据的对象
        username: '',
      // },
      // tempSearchObj: {
      //   // 收集搜索条件输入的对象
      //   username: '',
      // },
      selectedIds: [], // 所有选择的user的id的数组
      tableData: [],
      // 总条数
      total: 30,
      // 当前页
      page: 1,
      // 每页展示几条数据
      limit: 3,
      isEdit:false,//是否为修改状态
      dialogUserVisible: false, // 是否显示用户添加的dialog
      dialogUpdataUserVisible: false, //是否显示修改的用户的dialog
      dialogRoleVisible: false, //是否显示配置角色的dialog
      user: {
        nickName:'',
        password:'',
        username:''
      },
      userRules: {
        // 用户添加/修改表单的校验规则
        username: [
          { required: true, message: '用户名必须输入',trigger:'blur' },
          { min: 4, message: '用户名不能小于4位',trigger:'blur' },
        ],
        password: [
          { required: true,message:'密码必须输入',trigger:'blur'},
          {min:6,message:'密码不能小于6位',trigger:'blur'}
        ],
      },
      userRoleIds: [], // 用户的角色ID的列表
      allRoles: [], // 所有角色列表
      users:{},// 当前要操作的user
      isIndeterminate: false, // 是否是不确定的
      checkAll: false, // 是否全选
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.limit = val
      this.getUsers()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val
      this.getUsers()
    },
    // 根据输入进行搜索
    search(){
      const {username} =this
      // console.log(username);
      this.getUsers({username})
    },
    // 获取用户分页列表
    async getUsers(searchObj) {
      if (searchObj) {
        this.page = 1
      }
      const result = await userApi.getPageList(this.page, this.limit, searchObj)
      // console.log(result);
      this.tableData = result.data.items
      this.total = result.data.total
    },
 
    // 重置输入框搜索
    resetSearch(){
      this.username=''
      this.getUsers()
    },

    // 显示添加用户的界面
    showAddUser() {
      this.dialogUserVisible = true
      this.$nextTick(() => this.$refs.user.clearValidate())

    },
    // 显示更新用户的页面
    showUpdateUser(user) {
      this.user = cloneDeep(user)
      this.dialogUpdataUserVisible = true
     
    },
    //显示分配角色
    showAssignRole(user) {
      this.users=user
      this.dialogRoleVisible = true
      this.getRoles()
    },
    // 删除某个用户
    async removeUser(row) {

      await userApi.removeById(row.id)
      // 删除提示
      this.$message.success('删除成功')
      // 重新发送
      this.getUsers()
    },
    // 批量删除用户
     deleteUsers(){
      this.$confirm('确定删除吗?')
        .then(async () => {
          await userApi.removeUsers(this.selectedIds)
          this.$message.success('删除成功')
          this.getUsers()
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    // 列表选中状态发生改变的监听回调
    handleSelectionChange(selection){
      this.selectedIds = selection.map((item) => item.id)
    },
    //保存
    async addUser(){
      this.$refs.user.validate(async(valid)=>{
        if(valid){
          try {
            //发请求
            userApi.add(this.user)
            this.$message.success('保存成功')
            this.dialogUserVisible = false //关闭对话框
            this.getUsers() //更新列表数据
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
     },
    //  修改
    async updateUser(){
      // await userApi.update(this.user)
      // this.dialogUpdataUserVisible = false //关闭对话框
      // this.getUsers() //更新列表数据
      // this.user={}
      this.$refs.user.validate(async(valid)=>{
        if(valid){
          try { 
            // 发请求
            userApi.update(this.user)
            this.$message.success('更新成功')
            this.dialogUpdataUserVisible = false //关闭对话框
            this.getUsers() //更新列表数据
            this.user={}
          } catch (error) {
            this.$message.error('更新失败')
          }
        }
      })
    },
    // 获取用户的角色列表
    async getRoles(){
      const result = await userApi.getRoles(this.users.id)
      const { allRolesList, assignRoles } = result.data
      console.log(result);
      this.allRoles=allRolesList
      this.userRoleIds=assignRoles.map((item)=>item.id)
      this.checkAll= allRolesList.length===assignRoles.length
      this.isIndeterminate =assignRoles.length > 0 && assignRoles.length < allRolesList.length
    },
    // 角色列表选中项发生改变的监听
    handleCheckedChange(value){
      const { userRoleIds, allRoles } = this
      this.checkAll=userRoleIds.length ===allRoles.length && allRoles > 0
      this.isIndeterminate =userRoleIds.length > 0 && userRoleIds.length < allRoles.length
    },
    //    全选勾选状态发生改变的监听
    handleCheckAllChange(value) {
      // value 当前勾选状态true/false
      // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
      this.userRoleIds = value ? this.allRoles.map((item) => item.id) : []
      // 如果当前不是全选也不全不选时, 指定为false
      this.isIndeterminate = false
    },
    // 配置角色保存
    async assignRole(){
      const roleIds = this.userRoleIds.join(',')
      const result = await userApi.assignRoles(this.users.id,roleIds)
      console.log(result);
      this.$message.success('配置成功')
      this.dialogRoleVisible=false //关闭对话框
    },
    
  },
}
</script>

<style scoped>
.mr-50 {
  margin-right: 50px;
}
.mr-20 {
  margin-right: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.mb-30 {
  margin-bottom: 30px;
}
</style>